package nl.twingate.processrevivor.logic;

import java.util.List;

import nl.avics.paed.R;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

/**
     * This task will revive processes.
     * 
     * Please provide Resources > Arrays > Defaults with *packagename*;*packagename.app_main_activity* pairs to revive
     * 
     * @author Marijn Oosterveld
     *
     */
    public class ReviveProcessesByGUITask extends AsyncTask<String, String, Void>{
    	
    	Context parent;
    	int timeoutBeforeRevive = 2000;
    	String tag = "reviveProcessesTask";
    	
    	/*
    	 * Creates a new reviveProcesstask usign a context as a parent
    	 * From this parent, resources will be loaded to determine which processes will be revived.
    	 */
    	public ReviveProcessesByGUITask (Context parent){
    		this.parent = parent;
    	}

    	/*
    	 * Revive our processes in the background
    	 */
		@Override
		protected Void doInBackground(String... paramsa) {
			
			// Load our resources.
			Resources res = parent.getResources();
			String[] defaults = res.getStringArray(R.array.defaults);
			
			//Sleep our timeout
			try {
				timeoutBeforeRevive = Integer.parseInt(res.getString(R.string.sys_timoutBeforeReviveInMS));
				
				Thread.sleep(timeoutBeforeRevive);
			} catch (InterruptedException e1) {
				//Do nothing
			}
			
			
			//Check which processes are currently running:
			ActivityManager man = (ActivityManager) parent.getSystemService(parent.ACTIVITY_SERVICE);
			List<RunningAppProcessInfo> currentlyrunningapps = man.getRunningAppProcesses();
			
			//Load our keyvalue strings from our resources.
			for(String keyvalue : defaults){
				
				Log.i(tag,"Current: " + keyvalue);
				
				try{
					if(keyvalue != null){
						String[] tmp = TextUtils.split(keyvalue, ";");

						//Look into the activitymanager if this process is already running
						// If the process is running, then ok!
						boolean running = false;
						for(RunningAppProcessInfo info : currentlyrunningapps){
							if(info.processName.equals(tmp[0])){
								running = true;
								Log.i(tag,"Current: " + keyvalue + " IS RUNNING");
							}
							
						}
						
						//If the process was not running, revive it.
						if(!running){
							Log.w(tag,"Current: " + keyvalue + " IS  NOT RUNNING, reviving..");
							
							try{
								Intent intent = new Intent();
								intent.setComponent(new ComponentName(tmp[0],tmp[1]));
								intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
								intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
								parent.startActivity(intent);
							}catch(Exception e){
								Log.w(tag, "Could not start a process" + e.getMessage());
							}
						}
						
					}
				}catch(Exception e){
					Log.e("LOAD", "COULD NOT LOAD KEY|VALUE PAIR: " + keyvalue);
				}
				
			}
		
			
			return null;
		}
		
		/*
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
		
		/*
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			try {
				this.finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
    	
    }